package com.ddl.pay;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author <a href="mailto:zjggle@gmail.com">Richard Zhou</a>
 * @version 1.0
 * @CreationTime: 2015/9/11
 * @Description:
 */
public class XmlResponseHandler {

    private static Map<String, ResponseHandler<?>> map = new HashMap<String, ResponseHandler<?>>();

    @SuppressWarnings("unchecked")
    public static <T> ResponseHandler<T> createResponseHandler(final Class<T> clazz) {
        if (map.containsKey(clazz.getName())) {
            return (ResponseHandler<T>) map.get(clazz.getName());
        } else {
            ResponseHandler<T> responseHandler = new ResponseHandler<T>() {
                @Override
                public T handleResponse(HttpResponse response)
                        throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        String str = EntityUtils.toString(entity);
                        System.out.println(new String(str.getBytes("iso-8859-1"), "utf-8"));
                        Map<String,String> map=XMLBeanUtils.readStringXmlOut(str);
                        T obj=null;
                        try {
                            if (map != null) {
                                obj = clazz.newInstance();
                                Field[] fields = obj.getClass().getDeclaredFields();
                                for (Field field : fields) {
                                    int mod = field.getModifiers();
                                    if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                                        continue;
                                    }

                                    field.setAccessible(true);
                                    field.set(obj, map.get(field.getName()));
                                }
                            }
                        }catch (Exception e){
                            throw new ClientProtocolException("Unexpected respondse status: " + status);
                        }
                        return obj;
                    } else {
                        throw new ClientProtocolException("Unexpected respondse status: " + status);
                    }

                }
            };
            map.put(clazz.getName(), responseHandler);
            return responseHandler;
        }
    }

}
